'use strict';

const {
	verifyToken
} = require('wx-common')

exports.main = async (event, context) => {
	//event为客户端上传的参数
	const db = uniCloud.database();
	const dbCmd = db.command;

	const payload = verifyToken(event.token);
	const action = event.action;
	let resData = {}

	if (payload.type === 1 || payload.type === 2) {
		// token验证通过
		if (payload.type === 2) {
			// token即将过期返回新token
			resData.token = payload.newToken
		}
		if (action == "get") {
			// 获取菜单列表
			const dbRes = await db.collection('menus').where({
					owner: dbCmd.eq(payload.openid)
				})
				.orderBy("_id", "desc")
				.get()
			if (dbRes.affectedDocs < 1) {
				// 该用户没有菜单，生成默认菜单
				let foodsList = ['茄子', '土豆丝', '红烧肉', '丝瓜', '苦瓜', '红烧排骨', '回锅肉', '白菜', '生菜'];
				const dbAdd = await db.collection("menus").add({
					menus: [foodsList],
					owner: payload.openid
				})
				if (dbAdd.id) {
					resData.data = {
						menus: [foodsList],
						_id: dbAdd.id
					};
				} else {
					// 添加失败
					return {
						code: 201,
						msg: '获取失败',
						data: resData
					}
				}
			} else {
				// 已有菜单返回菜单
				delete dbRes.data[0]["owner"];
				resData.data = dbRes.data[0]
			}
		} else if (action == "update") {
			const dbUpdate = await db.collection("menus").where({
				"_id": dbCmd.eq(event._id),
				"owner": dbCmd.eq(payload.openid)
			}).update({
				menus: event.menus
			})

			// 获取菜单列表
			const dbRes = await db.collection('menus').where({
					owner: dbCmd.eq(payload.openid)
				})
				.orderBy("_id", "desc")
				.get()
			delete dbRes.data[0]["owner"];
			resData.data = dbRes.data[0]
		}
		// 返回菜单信息
		return {
			code: 200,
			msg: '获取成功',
			data: resData
		};
	} else if (payload.type === 0) {
		// token验证失败 需重新登录
		return {
			code: 203,
			msg: '请重新登录',
			data: resData
		};
	}
};
